/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package linkeddata.arida.ufc.br.test;

import java.io.File;
import java.io.FileWriter;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;

/**
 *
 * @author jeovane
 */
public class ModifyXML {

    /**
     * This method is used to read the dats from XML file
     */
    private void getXMLDetails() {
        try {
            /**
             * Initializing the SAXBuilder class
             */
            SAXBuilder builder = new SAXBuilder();
            String filePath = "/home/jeovane/sample.xml";
            File file = new File(filePath);
            if (file.exists()) {
                Document document = (Document) builder.build(file);

                /**
                 * Get the root element from the document class instance and
                 * from the root element get all the child elements and replace
                 * the appropriate values
                 */
//                Element root = document.getRootElement();
//                Element firstTag = root.getChild("firsttag");
//                firstTag.getAttribute("tag").setValue("file");
//                firstTag.getChild("firstsubtag").setText("This is the first sub tag");
//
//                Element secondTag = root.getChild("secondtag");
//                secondTag.setText("This is the second tag");
                
                Element threeTag = new Element("threeTag");
                threeTag.setAttribute(new Attribute("key", "threeTag"));
                
                document.getRootElement().addContent(threeTag);
                /**
                 * Print the modified xml document
                 */
                String des = new XMLOutputter().outputString(document);
                System.out.println("String: " + des);

                /**
                 * Modify the orginal document using FileWritter
                 */
                FileWriter fileWriter = new FileWriter(file);
                fileWriter.write(des);
                fileWriter.close();
            } else {
                System.out.println("File does not exist");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String argS[]) {
        try {
            new ModifyXML().getXMLDetails();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
